package com.yst.web.utils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public final class UrlUtil {
    public static String formatUrl(String url, String separator){
        String[] strings=url.split(separator);
        List<String> list= Arrays.stream(strings).filter((it)->!it.isEmpty()).collect(Collectors.toList());
        return String.join(separator,list);
    }

    public static String formatUrl(String url){
        return formatUrl(url,"/");
    }



    public static String comboPathUseSeparator(String separator,boolean prefix,boolean suffix,String...paths){
        List<String> pathList=new ArrayList<>();
        for(String path:paths) {
            String[] pathArray=path.split(separator);
            pathList.addAll(Arrays.stream(pathArray).filter((it)->!it.isEmpty()).collect(Collectors.toList()));
        }
        String result=String.join(separator, pathList);
        if (suffix){
            result= result.concat(separator);
        }
        if (prefix){
            result=separator.concat(result);
        }
        return result;
    }


    public static String comboPath(String separator,boolean prefix,boolean suffix,String...paths){
        return comboPathUseSeparator(separator,prefix,suffix,paths);
    }

    public static String comboPath(boolean prefix,boolean suffix,String...paths){
        return comboPathUseSeparator("/",prefix,suffix,paths);
    }

    public static String comboPath(boolean suffix,String...paths){
        return comboPathUseSeparator("/",false,suffix,paths);
    }

    /**
     * combination path
     * @param paths path array
     * @return full path
     */
    public static String comboPath(String...paths){
        return comboPathUseSeparator("/",false,false,paths);
    }

    public static String ObjectToUrlParams(Object obj){
        Map<String, Field> fieldMap=ClassUtils.getClassFields(obj.getClass());
        List<String> paramList=new ArrayList<>();
        if (null!=fieldMap) {
            for (String key : fieldMap.keySet()) {
                paramList.add(key + "=" +  BeanUtils.getFieldValue(obj, key, "").toString());
            }
        }
        return String.join("&", paramList);
    }

}
